package tool

import (
	"bytes"
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/parnurzeal/gorequest"
	common "jihe.common"
	"jihe.common/oss"
	"jihe.common/protos/base_server/proto"
)

func SplitObj(objUrl string) (ret []*proto.BaseCutpart, err error) {
	defer func() {
		if err := recover(); err != nil {
			common.Loger.Error("SplitObj obj_url:%s err:%v", objUrl, err)
			return
		}
	}()
	_, txtContent, errs := gorequest.New().Timeout(time.Second * 30).Get(objUrl).End()
	if len(errs) != 0 {
		err = fmt.Errorf("%v_%s",errs[0],objUrl)
		return
	}
	rows := strings.Split(txtContent, "\n")
	items := make([]string, 0)
	groups := make(map[string][]string)
	groupName := ""
	groupNames := make([]string, 0)
	for rowDx, row := range rows {
		rowArr := strings.Split(row, " ")
		if rowArr[0] == "g" {
			groupName = rowArr[1]
		}
		if rowDx+1 == len(rows) {
			items = append(items, row)
			groups[groupName] = items
			items = make([]string, 0)
			groupNames = append(groupNames, groupName)
		} else {
			nextRow := strings.Split(rows[rowDx+1], " ")
			if rowArr[0] == "f" && nextRow[0] == "v" {
				items = append(items, row)
				groups[groupName] = items
				items = make([]string, 0)
				groupNames = append(groupNames, groupName)
			} else {
				items = append(items, row)
			}
		}
	}
	vnum := 0
	groupFoffset := make(map[string]int)
	for nameDx, name := range groupNames {
		group := groups[name]
		//每个group需要偏移的v数量
		for _, item := range group {
			row := strings.Split(item, " ")
			if row[0] == "v" {
				vnum++
			}
		}
		if nameDx+1 == len(groupNames) {
			groupFoffset[groupNames[0]] = 0
		} else {
			groupFoffset[groupNames[nameDx+1]] = vnum
		}
	}
	for _, name := range groupNames {
		group := groups[name]
		//每个group需要偏移的v数量
		for itemIndex, item := range group {
			row := strings.Split(item, " ")
			if row[0] == "f" {
				fint, _ := strconv.Atoi(strings.Split(row[1], "/")[0])
				fint2, _ := strconv.Atoi(strings.Split(row[2], "/")[0])
				fint3, _ := strconv.Atoi(strings.Split(row[3], "/")[0])
				tempArr := fmt.Sprintf("f %d/%d/%d %d/%d/%d %d/%d/%d", fint-groupFoffset[name], fint-groupFoffset[name], fint-groupFoffset[name], fint2-groupFoffset[name], fint2-groupFoffset[name], fint2-groupFoffset[name], fint3-groupFoffset[name], fint3-groupFoffset[name], fint3-groupFoffset[name])
				groups[name][itemIndex] = tempArr
			}
		}
		bucket, e := oss.GetClient().Bucket("jihe-file")
		if e != nil {
			err = e
			return
		}
		path := fmt.Sprintf("%s/%d.obj", time.Now().Format("2006-01-02"), GetSnowflakeId())
		err = bucket.PutObject(path, bytes.NewReader([]byte(strings.Join(groups[name], "\n"))))
		if err != nil {
			return
		}
		baseCut := &proto.BaseCutpart{}
		baseCut.AlgorithmMethod = 1 //默认普通算法
		baseCut.Code = strings.TrimSpace(name)
		baseCut.ObjUrl = fmt.Sprintf("%s/%s", common.Configer.Oss.Domain, path)
		ret = append(ret, baseCut)
	}
	return
}

func GetCutPartVt(objUrl string) (ret [][]float64, err error) {
	defer func() {
		if err := recover(); err != nil {
			common.Loger.Error("GetCutPartVt obj_url:%s err:%v", objUrl, err)
			return
		}
	}()
	_, txtContent, errs := gorequest.New().Timeout(time.Second * 5).Get(objUrl).End()
	if len(errs) != 0 {
		err = errs[0]
		return
	}
	rows := strings.Split(txtContent, "\n")
	for _, row := range rows {
		rowArr := strings.Split(row, " ")
		if rowArr[0] == "vt" {
			vtx, _ := strconv.ParseFloat(rowArr[1], 64)
			vty, _ := strconv.ParseFloat(rowArr[2], 64)
			itemArr := []float64{vtx, vty}
			ret = append(ret, itemArr)
		}
	}
	return
}

//替换vt
func MakeAfterObj(objUrl string, vt [][]float64) (newObjurl string, err error) {
	defer func() {
		if err := recover(); err != nil {
			common.Loger.Error("MakeAfterObj obj_url:%s err:%v", objUrl, err)
			return
		}
	}()
	_, txtContent, errs := gorequest.New().Timeout(time.Second * 5).Get(objUrl).End()
	if len(errs) != 0 {
		err = errs[0]
		return
	}
	vtstrs := make([]string, 0)
	for _, v := range vt {
		vtRowArr := []string{"vt", strconv.FormatFloat(v[0], 'g', -1, 64), strconv.FormatFloat(v[1], 'g', -1, 64)}
		vtstrs = append(vtstrs, strings.Join(vtRowArr, " "))
	}
	vtNum := -1
	rows := strings.Split(txtContent, "\n")
	for dx, row := range rows {
		rowArr := strings.Split(row, " ")
		if rowArr[0] == "vt" {
			vtNum++
			rows[dx] = vtstrs[vtNum]
			if vtNum == len(vtstrs)-1 {
				break
			}
		}
	}

	bucket, err := oss.GetClient().Bucket("jihe-file")
	if err != nil {
		return
	}
	path := fmt.Sprintf("%s/%d.obj", time.Now().Format("2006-01-02"), GetSnowflakeId())
	err = bucket.PutObject(path, bytes.NewReader([]byte(strings.Join(rows, "\n"))))
	if err != nil {
		return
	}
	newObjurl = fmt.Sprintf("%s/%s", common.Configer.Oss.Domain, path)
	return
}

//替换vt
func MakeAfterObjByPath(objUrl string, vt [][]float64, path string) (newObjurl string, err error) {
	defer func() {
		if err := recover(); err != nil {
			common.Loger.Error("MakeAfterObj obj_url:%s err:%v", objUrl, err)
			return
		}
	}()
	_, txtContent, errs := gorequest.New().Timeout(time.Second * 5).Get(objUrl).End()
	if len(errs) != 0 {
		err = errs[0]
		return
	}
	vtstrs := make([]string, 0)
	for _, v := range vt {
		vtRowArr := []string{"vt", strconv.FormatFloat(v[0], 'g', -1, 64), strconv.FormatFloat(v[1], 'g', -1, 64)}
		vtstrs = append(vtstrs, strings.Join(vtRowArr, " "))
	}
	vtNum := -1
	rows := strings.Split(txtContent, "\n")
	for dx, row := range rows {
		rowArr := strings.Split(row, " ")
		if rowArr[0] == "vt" {
			vtNum++
			rows[dx] = vtstrs[vtNum]
			if vtNum == len(vtstrs)-1 {
				break
			}
		}
	}

	bucket, err := oss.GetClient().Bucket("jihe-file")
	if err != nil {
		return
	}
	err = bucket.PutObject(path, bytes.NewReader([]byte(strings.Join(rows, "\n"))))
	if err != nil {
		return
	}
	newObjurl = fmt.Sprintf("%s/%s", common.Configer.Oss.Domain, path)
	return
}

//将多个已经变了vt和v的部位obj合并到整个obj中，并生产新的obj存到订单
func ItemObjsMergeToObj(items []*proto.BaseNeedCutpart, objUrl string) (newObjurl string, err error) {
	defer func() {
		if err := recover(); err != nil {
			common.Loger.Error("ItemObjsMergeToObj obj_url:%s err:%v", objUrl, err)
			return
		}
	}()
	objUrl = strings.Replace(objUrl, "files.dizanz", "jihe-file.oss-cn-beijing-internal.aliyuncs", -1)
	splits := make([]string, len(items))
	for k, v := range items {
		splits[k] = fmt.Sprintf("g %s", v.Code)
	}
	_, objCons, errs := Request.Get(objUrl).Timeout(time.Second * 5).EndBytes()
	if len(errs) != 0 {
		err = errs[0]
		return
	}
	rowsVtIndexs := make(map[string][]int)
	vtindexs := make([]int, 0)
	rows := strings.Split(string(objCons), "\n")
	for rowNum, row := range rows {
		rowArr := strings.Split(row, " ")
		if rowArr[0] == "vt" {
			vtindexs = append(vtindexs, rowNum)
		}
		if rowArr[0] == "g" {
			rowsVtIndexs[strings.TrimSpace(rowArr[1])] = vtindexs
			vtindexs = make([]int, 0)
		}
	}

	itemVts := make(map[string][]string)
	for _, v := range items {
		_, itemObjCons, errs := Request.Get(v.AfterObj).Timeout(time.Second * 5).EndBytes()
		if len(errs) != 0 {
			err = errs[0]
			return
		}
		itemRows := strings.Split(string(itemObjCons), "\n")
		for _, itemRow := range itemRows {
			itemRowArr := strings.Split(itemRow, " ")
			if itemRowArr[0] == "vt" {
				if _, ok := itemVts[v.Code]; ok {
					itemVts[v.Code] = append(itemVts[v.Code], itemRow)
				} else {
					itemVts[v.Code] = []string{itemRow}
				}
			}
		}

	}

	for code, vtRowNum := range rowsVtIndexs {
		itemVtRows := itemVts[code]
		tempN := -1
		for _, n := range vtRowNum {
			tempN++
			rows[n] = itemVtRows[tempN]
		}
	}

	bucket, err := oss.GetClient().Bucket("jihe-file")
	if err != nil {
		return
	}
	path := fmt.Sprintf("%s/%d.obj", time.Now().Format("2006-01-02"), GetSnowflakeId())
	err = bucket.PutObject(path, bytes.NewReader([]byte(strings.Join(rows, "\n"))))
	if err != nil {
		return
	}
	newObjurl = fmt.Sprintf("%s/%s", common.Configer.Oss.Domain, path)
	return
}
